package sap.tested;

public class ThreadGroupExample
{
    public static class MyThread extends Thread
    {
        boolean suspended;
 
        MyThread(ThreadGroup tgOb, String threadname)
        {
            super(tgOb, threadname);
            System.out.println("New thread: " + this);
            suspended = false;
            start(); // Start the thread
        }
 
        public void run()
        {
            try
            {
                for (int i = 5; i > 0; i--)
                {
                    System.out.println(getName() + ": " + i);
                    Thread.sleep(1000);
                    synchronized (this)
                    {
                        while (suspended)
                        {
                            wait();
                        }
                    }
                }
            } catch (Exception e)
            {
                System.out.println("Exception in " + getName());
            }
            System.out.println(getName() + " exiting.");
        }
 
        void suspendMe()
        {
            suspended = true;
        }
 
        synchronized void resumeMe()
        {
            suspended = false;
            notify();
        }
    }
 
    public static void main(String[] args)
    {
        // first define two groups
        ThreadGroup groupA = new ThreadGroup("my group");
        ThreadGroup groupB = new ThreadGroup("your group");
 
        // then define some threads and assign them a group
        MyThread t1 = new MyThread(groupA, "t1");
        MyThread t2 = new MyThread(groupA, "t2");
        MyThread t3 = new MyThread(groupB, "t3");
        MyThread t4 = new MyThread(groupA, "t4");
 
        System.out.println("\nHere is output from list():");
        groupA.list();
        groupB.list();
 
        System.out.println("Suspending Group A");
        Thread tga[] = new Thread[groupA.activeCount()];
        groupA.enumerate(tga); // get threads in group
        for (int i = 0; i < tga.length; i++)
        {
            ((MyThread) tga[i]).suspendMe(); // suspend each thread
        }
 
        try
        {
            Thread.sleep(1000);
        } catch (InterruptedException e)
        {
            System.out.println("Main thread interrupted.");
        }
 
        System.out.println("Resuming Group A");
        for (int i = 0; i < tga.length; i++)
        {
            ((MyThread) tga[i]).resumeMe();
        }
 
        try
        {
            System.out.println("Waiting for threads to finish.");
            t1.join();
            t2.join();
            t3.join();
            t4.join();
        } catch (Exception e)
        {
            System.out.println("Exception in Main thread");
        }
        System.out.println("Main thread exiting.");
    }
 
}
